<template>
  <el-dialog title="问卷详情" :visible.sync="dialogVisible" width="80%">
    <div class="survey-detail">
      <h1>{{ selectedSurvey.name }}</h1>
      <p>{{ selectedSurvey.description }}</p>
      <div v-for="(question, index) in selectedSurvey.questions" :key="index" class="question-container">
        <div class="question-text">{{ question.text }}</div>
        <div v-if="question.type === 'single-choice'">
          <el-radio-group v-model="responses[index]">
            <el-radio v-for="(option, idx) in question.options" :key="idx" :label="option">{{ option }}</el-radio>
          </el-radio-group>
        </div>
        <div v-if="question.type === 'multiple-choice'">
          <el-checkbox-group v-model="responses[index]">
            <el-checkbox v-for="(option, idx) in question.options" :key="idx" :label="option">{{ option }}</el-checkbox>
          </el-checkbox-group>
        </div>
        <div v-if="question.type === 'fill-in-the-blank'">
          <el-input v-model="responses[index]" placeholder="请输入答案"></el-input>
        </div>
        <div v-if="question.type === 'ranking'">
          <draggable v-model="responses[index]" handle=".handle">
            <div v-for="(option, idx) in responses[index]" :key="idx" class="rank-item">
              <i class="el-icon-rank handle"></i> {{ option }}
            </div>
          </draggable>
        </div>
        <div v-if="question.type === 'rating'">
          <el-rate v-model="responses[index]" :max="5" show-score></el-rate>
        </div>
        <div v-if="question.type === 'dropdown'">
          <el-select v-model="responses[index]" placeholder="请选择">
            <el-option v-for="(option, idx) in question.options" :key="idx" :label="option" :value="option"></el-option>
          </el-select>
        </div>
        <div v-if="question.type === 'date-time'">
          <el-date-picker
            v-model="responses[index]"
            type="datetime"
            placeholder="选择日期时间"
          ></el-date-picker>
        </div>
      </div>
      <VerificationCode v-if="shouldShowVerification" @verified="onVerificationVerified" />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitResponses" :disabled="shouldShowVerification && !isVerified">提交</el-button>
      <el-button @click="closeDialog">关闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import draggable from 'vuedraggable';
import VerificationCode from './VerificationCode.vue';

export default {
  components: {
    draggable,
    VerificationCode
  },
  props: {
    answeredSurveys: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      selectedSurvey: {},
      responses: [],
      showVerification: false,
      isVerified: false
    };
  },
  computed: {
    shouldShowVerification() {
      return this.showVerification;
    }
  },
  methods: {
    open(survey) {
      this.selectedSurvey = survey;
      this.initializeResponses();
      this.checkIfNeedsVerification();
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    initializeResponses() {
      this.responses = this.selectedSurvey.questions.map((question, index) => {
        switch (question.type) {
          case 'single-choice':
            return null;
          case 'multiple-choice':
            return [];
          case 'fill-in-the-blank':
            return '';
          case 'ranking':
            return [...question.options];
          case 'rating':
            return 0;
          case 'dropdown':
            return '';
          case 'date-time':
            return '';
          default:
            return null;
        }
      });
      console.log(this.responses);
    },
    onVerificationVerified() {
      this.isVerified = true;
    },
    submitResponses() {
      const surveyId = this.selectedSurvey.id;
      const clientIp = this.getClientIp(); // 获取客户端IP

      if (this.hasAnsweredBefore(surveyId, clientIp)) {
        this.showVerification = true;
        if (!this.isVerified) {
          this.$message.error('请先通过验证码验证');
          return;
        }
      }

      // 检查所有必填项是否已填写
      for (const response of this.responses) {
        if (response === '' || response === null || (Array.isArray(response) && response.length === 0)) {
          this.$message.error('请填写所有必填项');
          return;
        }
      }

      // 这里可以处理提交逻辑，例如发送到服务器或本地存储
      console.log('Submitted Responses:', this.responses);

      // 假设这里有一个方法来处理提交逻辑
      this.handleFormSubmission({ surveyId, responses: this.responses });

      this.$emit('submitted', { surveyId: this.selectedSurvey.id, responses: this.responses });
      this.$message.success('问卷提交成功');
      this.closeDialog();
      this.storeAnsweredSurvey(surveyId, clientIp);
    },
    getClientIp() {
      // 这里可以使用一个服务来获取客户端IP，这里仅作示例
      return '127.0.0.1'; // 假设所有请求来自同一IP
    },
    hasAnsweredBefore(surveyId, clientIp) {
      const answers = this.answeredSurveys.filter(entry => entry.surveyId === surveyId && entry.clientIp === clientIp);
      return answers.length >= 1;
    },
    storeAnsweredSurvey(surveyId, clientIp) {
      this.$emit('storeAnsweredSurvey', { surveyId, clientIp });
    },
    checkIfNeedsVerification() {
      const surveyId = this.selectedSurvey.id;
      const clientIp = this.getClientIp(); // 获取客户端IP
      if (this.hasAnsweredBefore(surveyId, clientIp)) {
        this.showVerification = true;
      } else {
        this.showVerification = false; // 确保如果没有回答过，则不显示验证码
      }
    },
    handleFormSubmission(data) {
      // 这里可以添加实际的提交逻辑，例如发送数据到服务器
      console.log('Handling form submission:', data);
    }
  }
};
</script>

<style scoped>
.question-container {
  margin-bottom: 20px;
}

.rank-item {
  display: flex;
  align-items: center;
  cursor: move;
  padding: 5px;
  border: 1px solid #ccc;
  margin-top: 5px;
}

.handle {
  font-size: 20px;
  cursor: pointer;
}
</style>
